package user

/*
 * 用户模型
 * author cameron 
 */

import (
	"database/sql"
    "errors"
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql" // import your used driver
)

type User struct {
    Id   int
    Username string `orm:"size(32)"`
    Password string `orm:"size(50)"`
    Status  int
}


func init() {
    // register model
    orm.RegisterModel(new(User))
}

/* 
 *登陆判断
 */
func Logincheck(username string,password string) (User, error) {

    o := orm.NewOrm()
    var user User
    err := o.QueryTable("user").Filter("username", username).Filter("password", password).One(&user,"id","username")
    

    if err == orm.ErrNoRows {
        return user,errors.New("no data")
    }

    return user,err

}


/* 
 * 用户列表查询
 */
func ListAll() (num int64, err error, ops []User) {

    o := orm.NewOrm()

    var user []User
    num,err = o.QueryTable("user").All(&user)

    return num,err,user

}

/* 
 * 用户列表查询：可添加条件
 */
 func ListAllConn(username string) (num int64, err error, ops []User) {

    o := orm.NewOrm()

    var user []User
    num,err = o.QueryTable("user").Filter("username__contains",username).All(&user)

    return num,err,user

}

/* 
 * 用户删除
 */

func DelOne(id int) (int64,error) {

    o := orm.NewOrm()

    user := User{Id: id}
    num, err := o.Delete(&user)

    return num,err

}

func DelAll(ids string) (sql.Result,error) {

    o := orm.NewOrm()
    res, err := o.Raw("DELETE FROM user WHERE id IN ("+ids+")").Exec()
    
    return res,err

}

/*
 * 查询一条数据
 */
func ListOne(a int) (user User,err error) {
    o := orm.NewOrm()
    u := User{Id: a}
    err = o.Read(&u)
    return u,err
}

/*
 * 更新一条数据
 */
func UpdateOne(user User) (a int64,err error){

    o := orm.NewOrm()
    userinfo := User{Id: user.Id,Username: user.Username,Password: user.Password, Status: user.Status}

    num,err := o.Update(&userinfo)

    return num,err
}

/* 
 * 添加一条数据 
 */
func AddOne(user User) (int64,error) {
    o := orm.NewOrm()

    userinfo := User{Id: user.Id,Username: user.Username,Password: user.Password, Status: user.Status}

    id,err := o.Insert(&userinfo)

    return id,err
}

/*
 * 修改状态
 */
func UpdateStatus(user User) (num int64,err error) {
    o := orm.NewOrm()
    userinfo := User{Id: user.Id, Status: user.Status}

    num,err = o.Update(&userinfo,"status")

    return num,err
}

func ListCount() (int64,error) {

    o := orm.NewOrm()
    cnt, err := o.QueryTable("user").Count()
    return cnt,err

}

func ListCountConn(username string) (int64,error) {
    
    o := orm.NewOrm()
    cnt, err := o.QueryTable("user").Filter("username__contains",username).Count()
    return cnt,err

}










